package action;

import bean.*;
import dao.*;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by WeaponLin on 2015/11/19.
 */
public class ReaderAction extends SuperAction{
    public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
    public Date currentDate = Date.valueOf(dateFormat.format(System.currentTimeMillis()));

    public  String index(){
        return "index";
    }

    //查找准备，获取图书类别、出版社列表
    public String preSearch(){
        BookDAO bookDAO = new BookDAO();
        BookCategoryDAO bookCategoryDAO = new BookCategoryDAO();

        //查询类别列表
        List<BookCategory> categoryList = bookCategoryDAO.queryCategoryBySQL("categoryid is not NULL");
        if(categoryList.size() > 0){
            session.setAttribute("category_list",categoryList);
        }
        else
            session.setAttribute("category_list",null);

        //出版社列表
        List<Book> bookList = bookDAO.queryBookBySql("bookid is not NULL");
        Set<String> publishing = new HashSet<String>();
        for (int i = 0;i < bookList.size();i++){
            publishing.add(bookList.get(i).getPublishing());
        }
        if(publishing.size() > 0){
            session.setAttribute("publishing_list",publishing);
            return "pre_succ";
        }
        else {
            return "pre_fail";
        }
    }

    //图书查找
    public String bookSearch(){
        try {
            String sql = "bookid is not null";
            List<BookCategory> categoryList = null;
            String bookname = request.getParameter("bookname");
            String category = request.getParameter("category");
            String author = request.getParameter("author");
            String publishing = request.getParameter("publishing");

            if (!bookname.equals("")) {
                sql += " and bookname like'%" + bookname + "%'";
            }
            if (!author.equals("")) {
                sql += " and author like'%" + author + "%'";
            }
            if (!category.equals("") && !category.equals("全部")) {
                BookCategoryDAO categoryDAO = new BookCategoryDAO();
                categoryList = categoryDAO.queryCategoryBySQL("category='" + category + "'");
                String categoryid = null;
                if(categoryList.size() > 0){
                    categoryid = categoryList.get(0).getCategoryid();
                }
                sql += " and categoryid='" + categoryid + "'";
            }

            if (!publishing.equals("") && !publishing.equals("全部")) {
                sql += " and publishing='" + publishing + "'";
            }

            BookDAO dao = new BookDAO();
            List<Book> list = dao.queryBookBySql(sql);

                session.setAttribute("bookSearchResult", list);
            return "search_succ";

        } catch (Exception e) {
            return "failure";
        }
    }

    //历史借阅信息查询
    public String queryHistoryBorrow(){
        String readerid = request.getParameter("readerid");
        String state = null;
        try{
            state = session.getAttribute("isAdmin").toString();
        }
        catch (NullPointerException e){
            System.out.println(e.getMessage());
            return "fail";
        }

        if(readerid != null && !readerid.trim().equals("") && state == "false"){
            BorrowDAO borrowDAO = new BorrowDAO();
            List<Borrow> borrowList = borrowDAO.queryHistoryBorrow(readerid);

            session.setAttribute("borrow_list",borrowList);
            return "queryBorrow_succ";
        }
        else
            return "queryBorrow_fail";
    }

    //未还图书查询
    public String queryNoReturnBorrow(){
        String readerid = request.getParameter("readerid");
        String state = null;
        try{
            state = session.getAttribute("isAdmin").toString();
        }
        catch (NullPointerException e){
            System.out.println(e.getMessage());
            return "fail";
        }

        if(readerid != null && !readerid.trim().equals("") && state == "false"){
            BorrowDAO borrowDAO = new BorrowDAO();
            List<Borrow> borrowList = borrowDAO.queryNoReturnBorrow(readerid);
            if(borrowList.size() <= 0){
                session.setAttribute("noReturn_list",null);
                return "borrowNoReturn_fail";
            }
            for (int i=0;i < borrowList.size();i++){
                if(currentDate.getTime() > borrowList.get(i).getDatereturn().getTime()){
                    long day = (currentDate.getTime() - borrowList.get(i).getDatereturn().getTime())/(3600*24*1000);
                    borrowList.get(i).setDay(day);
                }
                else {
                    borrowList.get(i).setDay(0);
                }
            }
            session.setAttribute("noReturn_list",borrowList);
            return "borrowNoReturn_succ";
        }
        else
            return "borrowNoReturn_fail";
    }

    //个人信息查询
    public String queryReader(){
        Reader reader = (Reader)session.getAttribute("reader");
        if(reader == null){
            String readerid = null;
            try{
                readerid = session.getAttribute("loginName").toString();
            }
            catch (NullPointerException e){
                System.out.println(e.getMessage());
                return "queryReader_fail";
            }

            ReaderDAO readerDAO = new ReaderDAO();
            List<Reader> readerList = readerDAO.queryReaderBySql("readerid='"+readerid+"'");
            if(readerList.size() > 0){
                reader = readerList.get(0);
                session.setAttribute("reader", reader);
            }
            else
                return "queryReader_fail";
        }
        return "queryReader_succ";
    }

    //修改前准备
    public String preUpdate(){
        Reader reader = (Reader)session.getAttribute("reader");
        if(reader == null){
            return "preUpdate_fail";
        }
        String readerid = request.getParameter("readerid");
        UserDAO userDAO = new UserDAO();
        List<Users> users = userDAO.queryUserByName(readerid);
        if(users.size() > 0){
            session.setAttribute("user",users.get(0));
            return "preUpdate_succ";
        }
        else
            return "preUpdate_fail";
    }

    //个人信息修改
    public String updateReader(){
        Reader reader = null;
        Users user = null;
        String oldPassword = null, newPassword = null, rePassword = null;
        String phone = null, mobile = null;
        ReaderDAO readerDAO = new ReaderDAO();
        UserDAO userDAO = new UserDAO();

        try{
            reader = (Reader)session.getAttribute("reader");
            user = (Users)session.getAttribute("user");
            oldPassword = request.getParameter("oldPassword");
            newPassword = request.getParameter("newPassword");
            rePassword = request.getParameter("rePassword");
            phone = request.getParameter("phone");
            mobile = request.getParameter("mobile");
        }
        catch (NullPointerException e){
            e.printStackTrace();
            return "fail";
        }
        if(oldPassword != null && !oldPassword.trim().equals("")) {
            if (!oldPassword.equals(user.getPassword())) {
                this.addFieldError("oldPasswordError", "旧密码输入错误.");
                return "updateReader_fail";
            }
            else {
                if(newPassword == null || newPassword.equals("") || rePassword == null || rePassword.equals("")||
                        !newPassword.equals(rePassword)){
                    this.addFieldError("verifyPasswordError", "请输入新密码.");
                    return "updateReader_fail";
                }
                else{
                    user.setPassword(newPassword);
                    userDAO.updateUser(user);
                }
            }
        }

        if(!phone.equals(reader.getPhone()) && phone != null){
            reader.setPhone(phone);
            readerDAO.updateReader(reader);
        }

        if(!mobile.equals(reader.getMobile()) && mobile != null){
            reader.setMobile(mobile);
            readerDAO.updateReader(reader);
        }

        if (session.getAttribute("user") != null) {  //关闭用户登录相关信息
            session.removeAttribute("user");
        }
        return "updateReader_succ";
    }

}
